/**
 * Copyright (c) 2019 Coder League
 * All rights reserved.
 *
 * File：ApiRefundConsumer.java
 * History:
 *         2019年8月5日: Initially created, Chrise.
 */
package club.coderleague.ilsp.common.rocketmq.consumer;

import java.text.SimpleDateFormat;

import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import club.coderleague.ilsp.common.domain.beans.PaymentInterfaceResponse;
import club.coderleague.ilsp.service.orders.OrdersService;

/**
 * 接口退款消息消费者。
 * @author Chrise
 */
@Component
public class ApiRefundConsumer extends BaseDefaultMQPushConsumer {
	/**
	 * 消费者组。
	 */
	public static final String CONSUMER_GROUP = "API_REFUND_CONSUMER";
	/**
	 * 订阅主题。
	 */
	public static final String TOPIC = "API_REFUND_TOPIC";
	private static final String BODY_SPLIT = "_";
	private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
	
	@Autowired
	private OrdersService ordersService;
	
	/**
	 * 接口退款消息消费者构造方法。
	 */
	public ApiRefundConsumer() {
		super(CONSUMER_GROUP, TOPIC);
	}
	
	/**
	 * @see club.coderleague.ilsp.common.rocketmq.consumer.BaseDefaultMQPushConsumer#messageHandle(org.apache.rocketmq.common.message.MessageExt, org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext)
	 */
	@Override
	protected void messageHandle(MessageExt messageExt, ConsumeConcurrentlyContext consumeConcurrentlyContext) throws Exception {
		String body[] = new String(messageExt.getBody()).split(BODY_SPLIT);
		
		// 通知退款成功
		PaymentInterfaceResponse pir = new PaymentInterfaceResponse(Long.valueOf(body[0]), body[1], new SimpleDateFormat(DATE_FORMAT).parse(body[2]));
		this.ordersService.updateCompleteRefund(pir);
	}
	
	/**
	 * 生成消息体。
	 * @author Chrise 2019年8月5日
	 * @param pir 支付接口响应对象。
	 * @return 消息体字节数组。
	 */
	public static byte[] genBody(PaymentInterfaceResponse pir) {
		String time = new SimpleDateFormat(DATE_FORMAT).format(pir.getTradetime());
		String body = String.valueOf(pir.getOrderid()) + BODY_SPLIT + pir.getTradeno() + BODY_SPLIT + time;
		return body.getBytes();
	}
}
